package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.ClassifyAdapter;
import com.supor.aiot.food.adapter.ClassifyRightAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.ChildListBean;
import com.supor.aiot.food.bean.RecipeDeviceBean;
import com.supor.aiot.food.utils.TopLinearSmoothScroller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ClassifyActivity extends BaseActivity {

    CustomTitleBar toolbar;
    RecyclerView rvClassifyLeft;
    RecyclerView rvClassifyContent;
    private List<ChildListBean> classifyList;
    private List<RecipeDeviceBean> recipeDeviceList =new ArrayList<>();
    private ClassifyAdapter classifyAdapter;
    private ClassifyRightAdapter classifyRightAdapter;
    private boolean mIsFromClick;
    private LinearLayoutManager manager;
    private static final String CLASSIFY_POSITION="CLASSIFY_POSITION";
    private static final String CLASSIFY_DATA="CLASSIFY_DATA";
    private static final String CLASSIFY_SECOND_DATA="CLASSIFY_SECOND_DATA";
    private static final String CLASSIFY_SECOND_POSITION="CLASSIFY_SECOND_POSITION";
    private static final String DEVICE_RECIPE = "DEVICE_RECIPE";
    private static final String DEVICE_RECIPE_NAME = "DEVICE_RECIPE_NAME";
    private int iPosition = 0;
    private int sPosition = 0;
    @Override
    protected int resourceId() {
        return R.layout.activity_classify;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(resourceId());
        initView();
        initClassifyData();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar = findViewById(R.id.classify_toolbar);
        rvClassifyLeft = findViewById(R.id.rv_classify_left);
        rvClassifyContent = findViewById(R.id.rv_classify_content);
        toolbar.setIvLeftOnClickListener(view -> ClassifyActivity.this.finish());
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initRecycleView() {
        classifyAdapter=new ClassifyAdapter(classifyList, ClassifyActivity.this, position -> {
            mIsFromClick = true;//不走onScrolled，防止来回调
            manager.scrollToPositionWithOffset(position,0);
            if (position != iPosition) {
                classifyList.get(iPosition).setClicked(false);
                classifyRightAdapter.notifyItemChanged(iPosition);
            }
            for (int i=0;i<classifyList.size();i++){
                if (i==position){
                    classifyList.get(i).setClicked(true);
                    classifyRightAdapter.notifyItemChanged(position);
                    iPosition = position;
                }else {
                    classifyList.get(i).setClicked(false);
                }
            }
            classifyAdapter.notifyDataSetChanged();
            rvClassifyLeft.postDelayed(run,500);
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(ClassifyActivity.this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        rvClassifyLeft.setLayoutManager(layoutManager);
        rvClassifyLeft.setAdapter(classifyAdapter);

        classifyRightAdapter=new ClassifyRightAdapter(ClassifyActivity.this, classifyList,recipeDeviceList, new ClassifyRightAdapter.OnClassifyItemClickListener() {
            @Override
            public void OnTopClicked(int origin,int position) {
                Intent intent = new Intent(ClassifyActivity.this,RecipeTagsActivity.class);
                intent.putExtra(CLASSIFY_SECOND_DATA,classifyList.get(origin));
                intent.putExtra(CLASSIFY_SECOND_POSITION,position + 1);
                startActivity(intent);
            }

            @Override
            public void OnDeviceClicked(String deviceModel,String deviceName) {
                Intent intent = new Intent(ClassifyActivity.this,RecipeTagsActivity.class);
                intent.putExtra(DEVICE_RECIPE,deviceModel);
                intent.putExtra(DEVICE_RECIPE_NAME,deviceName);
                startActivity(intent);
            }

            @Override
            public void OnClassifyClicked(int origin,int position) {
                Intent intent = new Intent(ClassifyActivity.this,RecipeTagsActivity.class);
                intent.putExtra(CLASSIFY_SECOND_DATA,classifyList.get(origin));
                intent.putExtra(CLASSIFY_SECOND_POSITION,position+1);
                startActivity(intent);
            }
        });

        manager = new LinearLayoutManager(this) {
            @Override
            public void smoothScrollToPosition(RecyclerView view, RecyclerView.State state, int position) {
                TopLinearSmoothScroller scroller = new TopLinearSmoothScroller(view.getContext());
                scroller.setTargetPosition(position);
                startSmoothScroll(scroller);
            }
        };
        manager.setOrientation(RecyclerView.VERTICAL);
        rvClassifyContent.setLayoutManager(manager);
        rvClassifyContent.setAdapter(classifyRightAdapter);

        rvClassifyContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mIsFromClick) {//防止来回调
                    return;
                }
                if (rvClassifyContent.isComputingLayout()) {
                    rvClassifyContent.post(() -> changePosition());
                } else {
                    changePosition();
                }
            }
        });

        // 防止数据刷新闪烁
        Objects.requireNonNull(rvClassifyContent.getItemAnimator()).setChangeDuration(0);
    }

    private void changePosition() {
        int firstPosition = manager.findFirstVisibleItemPosition();
        if (firstPosition != sPosition) {
            sPosition = firstPosition;
            if (sPosition != iPosition) {
                classifyList.get(iPosition).setClicked(false);
                classifyRightAdapter.notifyItemChanged(iPosition);
            }
            classifyList.get(firstPosition).setClicked(true);
            classifyRightAdapter.notifyItemChanged(firstPosition);
            iPosition = firstPosition;
        }
        for (int i=0;i<classifyList.size();i++){
            if (i==firstPosition){
                classifyList.get(i).setClicked(true);
            }else {
                classifyList.get(i).setClicked(false);
            }
        }
        classifyAdapter.notifyDataSetChanged();
    }

    public Runnable run = this::setOrigin;

    private void setOrigin(){
        mIsFromClick=false;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initClassifyData() {
        classifyList = (List<ChildListBean>) getIntent().getExtras().get(CLASSIFY_DATA);
        if (classifyList==null)classifyList=new ArrayList<>();
        if (classifyList.size()>0){
            ChildListBean listBean = classifyList.get(0);
            listBean.setClicked(true);
            classifyList.set(0,listBean);
        }
        initHotRecipe();
    }

    /**
     * 获取设备
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("AutoDispose")
    private void initHotRecipe(){
        SearchFoodImpl.getInstance().getRecipeDevice(100).subscribe(result -> {
            if (result.isSuccess()) {
                recipeDeviceList.clear();
                recipeDeviceList.addAll(result.data.rows);
                initRecycleView();
            } else {
                Log.e(TAG, "device rsult error");
            }
        }, throwable -> {
            Log.e(TAG, "device 查询失败: " + throwable.getMessage());

        });
    }
}
